package com.idea.relax.mybatis.toolkit;


import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

/**
 * @className: BeanHandler
 * @description:
 * @author: salad
 * @date: 2022/1/25
 **/
class PropertyDescriptorUtil {

	/**
	 * 设置bean的某个属性值
	 * @param bean
	 * @param filed
	 * @param args
	 * @throws Exception
	 */
    public static void setProperty(Object bean, String filed, Object... args) throws Exception {
        // 获取bean的某个属性的描述符
        PropertyDescriptor propDesc = new PropertyDescriptor(filed, bean.getClass());
        // 获得用于写入属性值的方法
        Method methodSetUserName = propDesc.getWriteMethod();
        // 写入属性值
        methodSetUserName.invoke(bean, args);
    }

	/**
	 * 获取bean的某个属性值
	 * @param bean
	 * @param userName
	 * @return
	 * @throws Exception
	 */
    public static Object getProperty(Object bean, String userName) throws Exception {
        // 获取Bean的某个属性的描述符
        PropertyDescriptor proDescriptor = new PropertyDescriptor(userName, bean.getClass());
        // 获得用于读取属性值的方法
        Method methodGetUserName = proDescriptor.getReadMethod();
        // 读取属性值
        return methodGetUserName.invoke(bean);
    }

	/**
	 * 通过内省设置bean的某个属性值
	 * @param bean
	 * @param field
	 * @param args
	 * @throws Exception
	 */
    public static void setPropertyByIntrospector(Object bean, String field, Object... args) throws Exception {
        PropertyDescriptor[] proDescrtptors = getPropertyDescriptors(bean);
        // 遍历属性列表，查找指定的属性
        if (proDescrtptors != null && proDescrtptors.length > 0) {
            for (PropertyDescriptor propDesc : proDescrtptors) {
                // 找到则写入属性值
                if (propDesc.getName().equals(field)) {
                    Method methodSetUserName = propDesc.getWriteMethod();
					// 写入属性值
                    methodSetUserName.invoke(bean, args);
                    break;
                }
            }
        }
    }

    public static PropertyDescriptor[] getPropertyDescriptors(Object bean) throws IntrospectionException {
        // 获取bean信息
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
        // 获取bean的所有属性列表
        return beanInfo.getPropertyDescriptors();
    }

	/**
	 * 通过内省获取bean的某个属性值
	 * @param bean
	 * @param field
	 * @return
	 * @throws Exception
	 */
    public static Object getPropertyByIntrospector(Object bean, String field) throws Exception {
        PropertyDescriptor[] proDescrtptors = getPropertyDescriptors(bean);
        if (proDescrtptors != null && proDescrtptors.length > 0) {
            for (PropertyDescriptor propDesc : proDescrtptors) {
                if (propDesc.getName().equals(field)) {
                    Method methodGetUserName = propDesc.getReadMethod();
                    return methodGetUserName.invoke(bean);
                }
            }
        }
        return null;
    }

}
